package io.cici.cc.mybatis.plus.core;

import io.cici.cc.mybatis.lite.executor.parameter.ParameterHandler;
import io.cici.cc.mybatis.lite.mapping.MappedStatement;
import io.cici.cc.mybatis.lite.mapping.Sql;
import io.cici.cc.mybatis.lite.mapping.SqlSource;
import io.cici.cc.mybatis.lite.parse.Node;
import io.cici.cc.mybatis.lite.session.Configuration;
import io.cici.cc.mybatis.lite.sql_source.XMLLanguageDriver;
import io.cici.cc.mybatis.plus.core.config.GlobalConfig;
import io.cici.cc.mybatis.plus.core.toolkit.CollectionUtils;
import io.cici.cc.mybatis.plus.core.toolkit.GlobalConfigUtils;
import io.cici.cc.mybatis.plus.core.toolkit.sql.SqlUtils;

import java.util.List;


public class MybatisXMLLanguageDriver extends XMLLanguageDriver {

    @Override
    public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, Sql sql) {
        // 使用 MybatisParameterHandler 而不是 ParameterHandler
        return new MybatisParameterHandler(mappedStatement, parameterObject, sql);
    }

    @Override
    public SqlSource createSqlSource(Configuration configuration, Node node, Class<?> parameterType) {
        MybatisXMLScriptBuilder builder = new MybatisXMLScriptBuilder(configuration, node, parameterType);
        return builder.parseScriptNode();
    }

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
        GlobalConfig.DbConfig config = GlobalConfigUtils.getDbConfig(configuration);
        if (config.isReplacePlaceholder()) {
            List<String> find = SqlUtils.findPlaceholder(script);
            if (CollectionUtils.isNotEmpty(find)) {
                script = SqlUtils.replaceSqlPlaceholder(script, find, config.getEscapeSymbol());
            }
        }
        return super.createSqlSource(configuration, script, parameterType);
    }
}
